<?php

//<editor-fold defaultstate="collapsed" desc="License & Copyright">
/*
 * @license
 */

/**
 *
 * @author Jevgeni Geimanen (jevgeni.geimanen@gmail.com)
 */
//</editor-fold>
class SCEventDispatcher extends SCStruct {

    private $_EventListeners = array();

    /**
     *
     * @param string $eventName
     * @param object $obj
     * @param string $name
     * @return class_eventer 
     */
    public function addEventListener($eventName, &$obj, $name) {
        if (!is_array($eventName))
            $eventName = array($eventName);
        foreach ($eventName as $eName)
            SCArrayHelper::createArrayKeysTree($this->_EventListeners, array($this->getClassName(), $eName), array($obj, $name));
        return $this;
    }

    /**
     *
     * @param class_event $event
     * @return class_event 
     */
    public function fireEvent($event) {
        if (is_string($event))
            $event = new Event($event, $this);
        $event->eventer = $this;
        if (isset($this->_EventListeners[$this->getClassName()][$event->name])) {
            if (count($listeners = $this->_EventListeners[$this->getClassName()][$event->name]) > 0) {
                foreach ($listeners as $listener) {
                    $listener[0]->{$listener[1]}($event);
                }
            }
        }
        return $event;
    }

    protected function onEvent($name) {
        return $this->fireEvent($name);
    }

    /**
     *
     * @param string $name
     * @return bool 
     */
    protected function hasEvent($eventName) {
        $events = array_flip($this->getEventsSupported());
        return isset($events[$eventName]);
    }

    private $_EventsSupported;

    /**
     *
     * @return array 
     */
    protected function getEventsSupported() {
        if ($this->_EventsSupported === null) {
            $this->_EventsSupported = array();
            $constants = $this->getRefClass()->getConstants();
            foreach ($constants as $constantName => $constantValue)
                if (preg_match("/^EVENT_/", $constantName))
                    $this->_EventsSupported[$constantName] = $constantValue;
        }
        return $this->_EventsSupported;
    }

    private $_StatesSupported;

}

?>
